import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import Index from '../views/Index.vue'
import Staff from '../views/paysys/staff.vue'
import Layout from '../layout/index.vue'
import { nav } from '@/api/system/menu'
import { useMeanStore } from '@/store/menus'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'Login',
    meta: {
      title: '登录',
      keepAlive: true,
      requireAuth: false
    },
    component: () => import('@/views/login.vue')
  },
  {
    path: '/redirect',
    name: 'Redirect',
    component: Layout,
    children: [
      {
        path: '/index',
        name: 'Index',
        meta: {
          title: "首页"
        },
        component: Index
      },
    ]
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        component: Staff,
        name: 'Dashboard',
        meta: { title: '首页', icon: 'index', affix: true, noCache: true }
      }
    ]
  },
  {
    path: '/user',
    component: Layout,
    redirect: 'noredirect',
    children: [
      {
        path: 'center',
        name: '个人中心',
        meta: {
          title: "个人中心"
        },
        component: () => import('@/views/sys/user/center.vue')
      },
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  let token = localStorage.getItem("token")
  const useMean = useMeanStore()
  console.log('hasRoute', useMean.hasRoute)
  if (to.path == '/login') {
    console.log("login!!!!!!!!!!!")
    next()
  } else if (!token) {
    console.log("还没有token！！！")
    next({path: "/login"})
  } else if (to.path == '/' || to.path == '') {
    next({path: '/'})
  } else if (!useMean.hasRoute) {
    nav().then(res => {
      useMean.setMenuList(res.data.nav)
      useMean.setPermList(res.data.authoritys)
      sessionStorage.setItem('permission',res.data.authoritys)
      res.data.nav.forEach((menu: { children: any[]; }) => {
        if (menu.children) {
          menu.children.forEach((e: any) => {
            if (!e.component) {
              return
            }
            let modules = import.meta.glob('../**/*.vue')
            let route:any = {
              name: e.name,
              path: e.path,
              meta: {
                icon: e.icon,
                title: e.title
              },
              // component: () =>import('../views/' + e.component +'.vue')
              // 然后动态路由的时候这样来取
              component: modules['../views/' + e.component +'.vue']
              

            }
            router.addRoute("Redirect", route)
            router.options.routes.push(route)
          })
        }
      })
    })
    useMean.changeRouteStatus(true)
    next({path: to.path})
  } else {
    console.log("已经有路由了------------")
    next()
  }
  
})

export default router
